package com.zhenyi.liuxue.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.zhenyi.core.RowHandler;
import com.zhenyi.core.VueUtils;
import com.zhenyi.liuxue.index.LXController;
import com.zhenyi.liuxue.interceptor.AuthInterceptor;

import cn.hutool.core.util.PageUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@Before(AuthInterceptor.class)
public class AdminController extends LXController {

	protected void genExcel(List<Record> items, String path, RowHandler rowHandler) {
		// List<Record> items = db.find(sqlPara);
		ArrayList<Map<String, Object>> rows = new ArrayList<>();
		for (Record record : items) {
			Map<String, Object> row = new LinkedHashMap<>();
			row = rowHandler.onRow(record, row);
			rows.add(row);
		}
		// 通过工具类创建writer
		ExcelWriter writer = ExcelUtil.getWriter(path);
		// 合并单元格后的标题行，使用默认标题样式
		// 一次性写出内容，使用默认样式，强制输出标题
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		renderFile(new File(path));
		return;
	}

	/**
	 * 是否需要下载
	 * 
	 * @return
	 */
	protected boolean isDownload() {
		return getParaToInt("dl", 0).equals(1);
	}

	protected void setData(String name, Object info) {
		if (info == null) {
			return;
		}
		String json = VueUtils.getVueData(info);
		setAttr(name, json);
	}

	protected Integer getPageSize() {
		int pageSize = getParaToInt("pageSize", PAGE_SIZE);
		setAttr("pageSize", pageSize);
		return pageSize;
	}

	protected void setRainbow(Page<?> pages) {
		Integer requestPage = getParaToInt("page");

		HttpServletRequest request = getRequest();
		String url = request.getRequestURL().toString();
		String queryurl = request.getQueryString();
		if (StrKit.notBlank(queryurl)) {
			if (requestPage != null) {
				queryurl = queryurl.replace("&page=" + requestPage, "");
				queryurl = queryurl.replace("page=" + requestPage, "");
				if (StrKit.notBlank(queryurl)) {
					url = url + "?" + queryurl + "&page=";
				} else {
					url = url + "?page=";
				}
			} else {
				url = url + "?" + queryurl + "&page=";
			}
		} else {
			url = url + "?page=";
		}
		int pageTotal = pages.getTotalPage();
		int pageTotalRow = pages.getTotalRow();
		int page = pages.getPageNumber();
		int[] rainbow = PageUtil.rainbow(pages.getPageNumber(), pageTotal);
		setAttr("rainbow", rainbow);
		setAttr("pageUrl", url);
		setAttr("pageTotalRow", pageTotalRow);
		setAttr("pageSize", pages.getPageSize());
		setAttr("pageCurrent", page);
	}

	/**
	 * 跳转过来的页面 referer
	 * 
	 * @Time 2018年11月24日 上午10:40:29
	 */
	protected void setReferer() {
		setAttr("referer", getRequest().getHeader("Referer"));
	}
}
